package cn.johnyu.order.controller;

import cn.johnyu.commons.dto.ProductDto;
import cn.johnyu.order.client.AccountClient;
import cn.johnyu.order.client.ProductClient;
import cn.johnyu.order.domain.Order;
import cn.johnyu.order.po.OrderPo;
import cn.johnyu.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ProductClient productClient;
    @Autowired
    private AccountClient accountClient;
    @GetMapping("/info")
    public Map<String,String> info(){
        Map<String,String> map=new HashMap<>();
//        String info1 = restTemplate.getForObject("http://product-service/info", String.class);
        String info1 = productClient.info();
        String info2 = accountClient.info();
        map.put("product",info1);
        map.put("account",info2);
        return map;
    }

    @ExceptionHandler(value = SocketTimeoutException.class)
    public String handler1(Exception e){
        return "因为超时而导致异常。。。";
    }

    @GetMapping("/products/{id}")
    public ProductDto loadProduct(@PathVariable("id") int id){
        return productClient.loadProduct(id);
    }

    @GetMapping("/orders/{id}")
    public ResponseEntity<Order> loadOrder(@PathVariable("id") int id){
        return ResponseEntity.status(203).body(orderService.loadOrder(id));
    }
    @GetMapping("/orders")
    public ResponseEntity<List<OrderPo>> findAllOrders(){
        return ResponseEntity.ok(orderService.findAllOrders());
    }

    @PostMapping("/orders")
    public ResponseEntity<OrderPo> addOrder(int aid,int pid,int count){
        OrderPo po = orderService.createOrder(aid, pid, count);
        return ResponseEntity.ok(po);
    }

}
